import React, { useState, useRef } from 'react'
import ResizeBar from '../ResizeBar'
import {TelescopicProps} from './interface'
import preClassName from '../../../utils/preClassName'
import './style.sass'

const DEFAULT_MIN_WIDTH = 150;
const DEFAULT_MAX_WIDTH = 600;

const Telescopic: React.FC<TelescopicProps> = ({minW, maxW, children}) => {
  const [width, setwidth] = useState(minW || DEFAULT_MIN_WIDTH);
  const eleRef = useRef<HTMLDivElement>(null)
  const MINW = minW || DEFAULT_MIN_WIDTH;
  const MAXW = maxW || DEFAULT_MAX_WIDTH;

  return (
    <div ref={eleRef} className={preClassName('telescopic')} style={{width}}>
      <div className={preClassName('telescopic-inner')}>
        {children}
      </div>
      <ResizeBar
        tagName='i'
        className={preClassName('telescopic-resizebar')}
        cursor="col-resize"
        onChange={e => {
          const rect = eleRef.current!.getBoundingClientRect();
          if(e.endX >= rect.left + MINW && e.endX <=  rect.left + MAXW) {
            setwidth(Math.max(MINW, Math.min(MAXW, e.currentMoveX + width)))
          }
        }}
      />
    </div>
  )
}

export default Telescopic
